﻿using HCQ2_Model;
using HCQ2_Model.Student;
using HCQ2_Model.ViewModel;
using HCQ2UI_Logic.BaseController;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using HCQ2_Common;
using System.Web;
using System.IO;
using System.Data;
using HCQ2_Model.ViewModel.SysAdmin;
using System.Diagnostics;
using HCQ2_Common.Log;
using System.Transactions;

namespace HCQ2UI_Logic.ExperienceController
{
    /// <summary>
    /// 学生
    /// </summary>
    public class StudentController: BaseSchoolController
    {
        public ActionResult Index()
        {
            //所属学校列表
            var unitLists = ListBySchool();

            ViewBag.units = unitLists;
            return View();
        }

        /// <summary>
        /// 新增或修改
        /// </summary>
        /// <param name="id">为空新增，不为空修改</param>
        /// <returns></returns>
        public ActionResult dialog(Nullable<int> id)
        {
            //所属学校列表
            var unitLists = ListBySchool();
            ViewBag.units = unitLists;

            if (id != null)
            {
                ViewBag.id = id;
            }

            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult list(StudentListQuery query)
        {
            query.currentUserId = operateContext.Usr.user_id;
            TableModel tableModel = operateContext.bllSession.T_Student.GetStudentList(query);

            return operateContext.ok(tableModel);
        }

        /// <summary>
        /// 新增、更新
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult save(StudentEdit data)
        {
            data.updateUser = operateContext.Usr.user_name;
            if (data.id == null)
            {
                int id = operateContext.bllSession.T_Student.addStudent(data);
                //新增账号
                UserModel userModel = new UserModel();
                userModel.login_name = data.studentId;
                userModel.user_name = data.studentName;
                userModel.user_pwd = data.studentId;
                if (data.sex != null && data.sex == true)
                {
                    userModel.user_sex = "男";
                }
                if (data.sex != null && data.sex == false)
                {
                    userModel.user_sex = "女";
                }
                userModel.user_identify = data.idCode;
                userModel.user_type = "学生";
                userModel.user_role = "9";
                operateContext.bllSession.T_User.AddUser(userModel);

                return operateContext.ok(id);
            }
            else {
                int id = operateContext.bllSession.T_Student.updateStudent(data);
                return operateContext.ok(id);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult del(int id)
        {
            operateContext.bllSession.T_Student.delStudent(id);
            return operateContext.ok();
        }
        /// <summary>
        /// 通过ID获取数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult find(Nullable<int> id)
        {
            T_Student data = operateContext.bllSession.T_Student.FindSingle(w => w.id == id.Value);
            var classList = operateContext.bllSession.T_Student.ListBySchoolClass(data.schoolName);

            StudentFindData findData = data.MapTo<StudentFindData>();
            findData.classList = classList;
            return operateContext.ok(findData);
        }

        /// <summary>
        /// 获取学校下面的班级
        /// </summary>
        /// <param name="school"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult getSchoolClass(string school)
        {
            var data = operateContext.bllSession.T_Student.ListBySchoolClass(school);

            return operateContext.ok(data);
        }

        [HttpPost]
        public JsonResult importStudent(HttpPostedFileBase excelFile, string schoolName, int classId)
        {
            if (excelFile == null)
            {
                return operateContext.error("导入文件为空");
            }
            if (!Path.GetExtension(excelFile.FileName).Equals(".xlsx"))
            {
                return operateContext.error("导入文件是.xlsx格式的excel文件");
            }
            //导入人员批处理代码、导入文件名称
            string batchCode = Guid.NewGuid().ToString();

            Directory.CreateDirectory(Server.MapPath("~/Student/temp/"));
            //导入文件到临时目录
            string tempPath = Server.MapPath("~/Student/temp/") + batchCode + ".xlsx";
            excelFile.SaveAs(tempPath);

            using (TransactionScope tran = new TransactionScope())
            {
                List<UserModel> addUserList = new List<UserModel>();
                Stopwatch sw1 = new Stopwatch();
                sw1.Start();
                List<string> mess = operateContext.bllSession.T_Student.importStudent(tempPath, schoolName, classId, operateContext.Usr.user_name, ref addUserList);
                sw1.Stop();
                LogHelper.InfoLog(string.Format("导入学生数据，耗时：{0} 毫秒。", sw1.ElapsedMilliseconds));
                try
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    operateContext.bllSession.T_Student.createStudentUser(addUserList);
                    sw.Stop();
                    LogHelper.InfoLog(string.Format("导入学生数据，生成账号，耗时：{0} 毫秒。", sw.ElapsedMilliseconds));
                    tran.Complete();
                }
                catch (Exception e)
                {
                    if (mess.Count == 0)
                    {
                        mess.Add(string.Format("创建账号出现错误：" + e.Message));
                    }
                    else
                    {
                        mess.Add(string.Format("创建账号出现错误：" + e.Message));
                    }
                }
                return operateContext.ok(mess);
            }
            
        }
    }
}
